//
//  BHPersonalChildViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/19.
//

import UIKit

class BHPersonalChildViewController: BHBaseViewController {
   
    var canSuperScollingActBlock:(() -> Void)?
    
    lazy var waterFlowLayout: DPHomeWaterFlowLayout = {
        let layout = DPHomeWaterFlowLayout.init()
        layout.delegate = self
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let view = UICollectionView.buildCollectionView(layout: self.waterFlowLayout)
        view.backgroundColor = .color_f8f8f8
        view.register(UINib.init(nibName: "BHHomeCircleItemCell", bundle: nil), forCellWithReuseIdentifier: "BHHomeCircleItemCell")

        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    lazy var serviceManager: BHCircleServiceManager = {
        let manager = BHCircleServiceManager.init()
        return manager
    }()
    
    var userid: String?
    var childType: Int = 0
    open var childCanScorll: Bool = false
    fileprivate var columnListArray: [BHCircleListModel] = []

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if self.childType == 0 {
            NotificationCenter.default.removeObserver(self)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.childType == 0 {
            NotificationCenter.default.addObserver(self, selector: #selector(forceRefresh), name: NSNotification.Name.init(String.deleteSelfCircleKey), object: nil)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.removeFromSuperview()
        
        self.view.addSubview(self.collectionView)
        
        self.loadPersonalCircleService()
        
        // 点赞的回调
        self.serviceManager.circleLikeOrNotResponseBlock = {[weak self] (success, errorMsg) in
            self?.collectionView.reloadData()
        }
        
        self.collectionView.addRefresh { [weak self] in
            self?.page = 1
            self?.loadPersonalCircleService()
        }
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            self?.loadPersonalCircleService()
        }
    }
    
    @objc func forceRefresh() {
        self.page = 1
        self.loadPersonalCircleService()
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: self.view.bh_height)
    }
   
}

extension BHPersonalChildViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.childCanScorll == false{
            scrollView.contentOffset.y = 0
        }else {
            if scrollView.contentOffset.y <= 0 {
                self.childCanScorll = false
                self.canSuperScollingActBlock?()
            }
        }
    }
    
}

extension BHPersonalChildViewController: DPHomeWaterFlowLayoutDelegate {
    
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        let model = self.columnListArray[indexPath.row]
        return  BHHomeCircleItemCell.circleHeight+model.textHeight+58
    }
    
    func columnNumber(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> Int {
        return 2

    }
    
    func interitemSpacing(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> CGFloat {
        return 8

    }
    func lineSpacing(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> CGFloat {
        return 10

    }
    func insetForSection(collectionView collection: UICollectionView, layout: DPHomeWaterFlowLayout, section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)
    }
}

extension BHPersonalChildViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.columnListArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = self.columnListArray[indexPath.row]
        let halfW = (UIScreen.width-40)/2.0
        return  CGSize(width: halfW-1, height: BHHomeCircleItemCell.circleHeight+model.textHeight+58)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("点击：\(indexPath.row)")
        
        let model = self.columnListArray[indexPath.row]
        BHRouter.shared.bh_goCircleDetail(circleId: model.circleId)
    }
}

extension BHPersonalChildViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHHomeCircleItemCell", for: indexPath) as! BHHomeCircleItemCell
        let model = self.columnListArray[indexPath.row]
        cell.circleModel = model
        cell.likeBtn.addBtnAction(action: {[weak self] (_) in
            self?.serviceManager.circleLikeOrNot(model: model)
        }, for: .touchUpInside)
        return cell
    }
    
    
    
}


extension BHPersonalChildViewController {
    func loadPersonalCircleService()  {
        var dic: [String: Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        if self.userid != nil {
            dic["userId"] = self.userid!
        }
        
        var url: String = String.me_userInfo_selfCircle_list_url
        
        if self.childType == 1 {
            url = String.me_userInfo_likeCircle_list_url
        }
        let manager = BHHTTPClient.init()
        manager.get(url: url, paramters: dic) { (success, errorMsg, responseDic) in
            self.collectionView.endRefresh()
            self.collectionView.endLoading()
            
            if success == true {
                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.columnListArray.count != 0 {
                        self.columnListArray.removeAll()
                    }
                }
              
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: responseDic, key: "total")
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
               
                for item in record {
                    let model = BHCircleListModel.init()
                    model.parseDic(item as! [String:Any])
                    self.columnListArray.append(model)
                }
                
                self.collectionView.reloadData()
                if self.columnListArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
             
            }else {
                BHToast.toast(text: errorMsg) 
                if self.page > 1 {
                    self.page -= 1
                }
            }
        }
        
    }
}
